<?php
// Session log in
session_start();
$login_state = 'new';

require ('../../config/mysqli_connect.php'); // Connect to the db.

$email_valid = true;

// Check if the email is misformatted
if (count($_POST) > 0) {
    $email_regx = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/';
    $email_valid = (preg_match($email_regx, $_POST['email']) > 0);
}

if (count($_POST) > 0 and $email_valid) {
    // This section is executed upon form submission
    $escaped_email = mysqli_real_escape_string($dbc,$_POST['email']); // regex
    $q = "select User_password from Users where User_email = '$escaped_email'";
    $r = @mysqli_query($dbc, $q);
    $selected_user = mysqli_fetch_array($r, MYSQLI_NUM);

    if (sha1($_POST['pass']) == $selected_user[0]) {
        $login_state = 'success';
        $_SESSION['login'] = 'valid';
    } else {
        $login_state = 'failure';
    }
}
mysqli_close($dbc); // Close the database connection.

if ($login_state == 'success') {
    // If login was successful, set login session and redirect
    header("Location: index.php");
}

$page_title = 'Login';

include('includes/header.html');

if (!$email_valid) {
    // If there was a problem with the email format, give an error
    echo "<p class=\"error\">Error: Not a valid email address</p>\n";
}


if ($login_state == 'failure') {
    // If login was a failure, give an error
    echo "<p class=\"error\">Error: Authentication failed</p>\n";
}
?>

<h1>Login</h1>
<form action="login.php" method="post">
    <p>Email Address: <input type="text" name="email" size="20" maxlength="60" /> </p>
    <p>Password: <input type="password" name="pass" size="20" maxlength="20" /></p>
    <p><input type="submit" name="submit" value="Login" /></p>
</form>

<?php include ('includes/footer.html'); ?>
